﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IBS.Model;
using IBS.Model.Base;
using IBS.ServiceContracts;
using IBS.Bll.Tools;
using log4net;

namespace IBS.Bll.KnowledgeBase
{
    public class AddressService : ServiceBase, IAddressService
    {
        private readonly IStreetService _streetService;
        private ILog log = LogManager.GetLogger(typeof (AddressService));
        #region Constructors
        public AddressService(IIbsContext context, IStreetService streetService) : base(context)
        {
            _streetService = streetService;
        }

        #endregion

        #region Members
        public IList<Address> GetAddresses (Func<Address, bool> criteria = null, int? page =null )
        {
            log.InfoFormat("GetAddressesByCriteria");

            return _context.Addresses.GetByCriteria(page, criteria);

        }
        #endregion

        public Address CreateAddress(string operatorLogin, int streetId, int house, int? housing = null, int? apartment = null)
        {
            Street street = _streetService.GetStreetById(streetId);
            var address = new Address()
            {
                Street = street,
                House = house,
                Housing = housing,
                Apartment = apartment,
                UpdateLogin = operatorLogin
            };
            _context.Addresses.AddObject(address);
            _context.SaveChanges();
            return address;
        }

        public Address GetAddressById(int addressId)
        {
            try
            {
                return _context.Addresses.Single(a => a.Id == addressId);
            }
            catch (InvalidOperationException)
            {
                throw new BusinessException("Address does not exist");
            }
        }
    }
}
